<?php

class Common_DataTable_Model_Mixin_GroupMeta {
    
    private $arr_meta = null;
    
    public function __construct() {
    }
    
    public function groupDataBy($mix_meta) {
        $this->arr_meta = (array) $mix_meta;
    }
    
    public function hasGroupDefinition() {
        return !is_null($this->arr_meta);
    }
    
    public function getGroupDefinition() {
        return $this->arr_meta;
    }
    
    public function generateDataGroups($arr_data) {
        
        $arr_rows = array();
        $arr_groups = array();

        if($this->hasGroupDefinition()) {
        
            $arr_grouping_keys = $this->getGroupDefinition();
        
            foreach ($arr_data as $str_data_key => $arr_row) {
        
                $arr_keys = array();
        
                $int_group_depth = 1;
                foreach($arr_grouping_keys as $str_grouping_index => $str_grouping_key) {
        
                    if(is_integer($str_grouping_index)) {
                        $str_grouping_index = $str_grouping_key;
                    }
        
                    $mix_group_index = isset($arr_row[$str_grouping_index]) ? $arr_row[$str_grouping_index] : null;
                    $mix_group_value = isset($arr_row[$str_grouping_key]) ? $arr_row[$str_grouping_key] : null;
        
                    $arr_keys[] = $mix_group_index;
        
                    $str_group_key = implode('|', $arr_keys);
        
                    if(!isset($arr_groups[$str_group_key])) {
                        $arr_groups[$str_group_key] = array(
                            'label' => $mix_group_value,
                            'depth' => $int_group_depth,
                            'count' => 0
                        );
                        $arr_rows[$str_group_key] = array();
                    }
        
                    $int_group_depth++;
                }
        
                $arr_rows[$str_group_key][$str_data_key] = $arr_row;
                $arr_groups[$str_group_key]['count']++;
                
                
            }
        
        } else {
            $arr_rows = array(
                null => $arr_data
            );
        }
        
        return array(
            'groups' => $arr_groups,
            'rows' => $arr_rows
        );
        
    }
       
}